<template>
    <scroll-view scroll-y class="confirm-order-container"
        :scroll-with-animation="true"
        :style="{ paddingBottom: safeAreaInsets?.bottom + 90 + 'rpx' }"
    >
        <!-- 地址信息区域 -->
        <view class="address-wrap">
            <view class="title">收货地址</view>
            <view class="content" v-if="userStore.deliveryAddr.id" @click="handleShowChooseDeliveryAddrPopup">
                <view class="address-icon">
                    <text class="iconfont icon-dizhi"></text>
                </view>
                <view class="address-left">
                    <div class="top ellipsis-2">{{userStore.deliveryAddr.region}} {{ userStore.deliveryAddr.address }}</div>
                    <div class="bottom">
                        <text class="name">{{userStore.deliveryAddr.name}}</text>
                        <text>{{userStore.deliveryAddr.mobile}}</text>
                    </div>
                </view>
                <view class="address-right">
                    <text class="icon iconfont icon-youjiantoucu"></text>
                </view>
            </view>

            <view class="choose" v-else>
                <text class="choose-btn"  @click="handleShowChooseDeliveryAddrPopup">选择收货地址</text>
            </view>


        </view>
        <!-- 选择收货地址弹层 -->
        <uni-popup 
            ref="popup" 
            type="top" border-radius="10px 10px 0 0"
            background-color='#fff' :mask-click="false"
        >
            <view class="address-title">
                <!-- 标题 -->
                <text class="title">选择收货地址</text>
                <!-- 关闭按钮 -->
                <text class="close iconfont icon-guanbi" @click="handleCloseAddressPopup"></text>
            </view>

            <!-- 收货地址列表开始 -->
            <view class="address-list-wrap">
                <template v-for="(item, index) in deliveryAddrList" :key="index">
                    <view class="address-item" :class="item.id == currentAddrId ? 'active': ''" @click="handleChooseDeliveryAddr(item)">
                        <view class="content-left">
                            <text class="iconfont icon-dizhi"></text>
                            <view class="content-box">
                                <view class="top">
                                    <text>{{item.region}} {{ item.address }}</text>
                                </view>
                                <view class="bottom">
                                    <text>{{item.name}}</text>
                                    <text class="mobile">{{ item.mobile }}</text>
                                </view>
                            </view>
                        </view>
                        <view class="content-right">
                            <uni-tag :mark="true" text="默认" type="error" size="mini" v-if="item.is_default" />
                        </view>
                    </view>
                </template>

                <view class="add-address">
                    <text class="add-btn"  @click="goto('/pagesUser/delivery_address/index')">新增收货地址+</text>
                </view>
            </view>
            <!-- 收货地址列表结束 -->
        </uni-popup>



        <!-- 订单信息区域 -->
        <view class="order-wrap">
            <uni-forms ref="formRef" :rules="rules" :modelValue="formData">
				<!-- 订购人姓名 -->
				<!-- <uni-forms-item :label-width="labelWidth" label="订购人姓名" required  name="name">
					<uni-easyinput :inputBorder="false" v-model="formData.name" :maxlength="30" placeholder="请输入订购人姓名" />
				</uni-forms-item> -->

				<!-- 订购人手机号 -->
				<!-- <uni-forms-item :label-width="labelWidth" label="订购人手机号" required  name="mobile">
					<uni-easyinput :inputBorder="false" v-model="formData.mobile" :maxlength="11" placeholder="请输入订购人手机号" />
				</uni-forms-item> -->

				<!-- 期望送达日期 -->
				<!-- <uni-forms-item :label-width="labelWidth" label="期望送达日期" required  name="date">
                    <uni-datetime-picker type="date" :clear-icon="false" v-model="formData.date"/>
				</uni-forms-item> -->

                <!-- 订单备注 -->
                <uni-section title="订单备注" padding>
                    <uni-easyinput type="textarea" autoHeight v-model="formData.note" placeholder="写上您的况福语,给心爱的他(她)送上份你的祝福(请勿填写特殊符号或表情符号)"></uni-easyinput>
                </uni-section>
			</uni-forms>
        </view>

        <!-- 商品信息区域，直接购买模式开始 -->
        <view class="goods-wrap" v-if="mode == 1">
            <navigator class="goods-item" :url="`/pagesGoods/goods_detail/index?id=${orderStore.createOrderParams.goods_id}`">
                <!-- 商品图片 -->
                <view class="cover-box">
                    <image class="cover" :src="orderStore.createOrderParams.cover_url"/>
                </view>

                <!-- 商品信息 -->
                <view class="goods-box">
                    <view class="top ellipsis-2">{{ orderStore.createOrderParams.name }}</view>
                    <view class="sku-txt">{{ orderStore.createOrderParams.goods_sepc_option_text }}</view>
                    <view class="bottom">
                        <view class="price-box">
                            <text class="symbol">￥</text>
                            <text class="price">{{ (orderStore.createOrderParams?.price/100).toFixed(2) }}</text>
                        </view>
                        <view class="num">x{{ orderStore.createOrderParams.num }}</view>
                    </view>
                </view>
            </navigator>
        </view>
        <!-- 商品信息区域，直接购买模式结束 -->

        <!-- 商品信息区域，购物车结算模式开始 -->
        <view class="goods-wrap" v-else>
            <view
                v-for="(item, index) in cartStore.checkedList"
                :key="index"
                class="goods-item"
                @click="goto(`/pagesGoods/goods_detail/index?id=${item.goods_id}`)"
            >
                <!-- 商品图片 -->
                <view class="cover-box">
                    <!-- #ifdef MP-WEIXIN -->
                    <image class="cover" :lazy-load="true" :src="global.FILE_DOMAIN + item.goods.cover_url"/>
                    <!-- #endif -->

                    <!-- #ifdef H5 -->
                    <img class="cover" v-img-lazy="global.FILE_DOMAIN + item.goods.cover_url" />
                    <!-- #endif -->
                </view>

                <!-- 商品信息 -->
                <view class="goods-box">
                    <view class="top ellipsis-2">{{ item.goods.name }}</view>
                    <view class="sku-txt">{{ item.goods_sepc_option_text }}</view>
                    <view class="bottom">
                        <view class="price-box">
                            <text class="symbol">￥</text>
                            <text class="price">{{ (item.goods.price/100).toFixed(2) }}</text>
                        </view>
                        <view class="num">x{{ item.num }}</view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 生成订单按钮 -->
        <view class="footer-wrap" :style="{ paddingBottom: safeAreaInsets?.bottom + 'rpx' }">
            <view class="left">
                <text class="symbol">￥</text>
                <text class="price" v-if="mode == 1">{{ ((orderStore.createOrderParams.price * orderStore.createOrderParams.num)/100).toFixed(2) }}</text>
                <text class="price" v-else >{{ (cartStore.checkedAmount/100).toFixed(2) }}</text>
            </view>
            <view class="right">
                <button class="btn" @click="handleCreateOrder">提交订单</button>
            </view>
        </view>
    </scroll-view>
</template>

<script setup lang="ts">
import { ref, inject, reactive } from 'vue'
import { useCartStore, useOrderStore, useUserStore } from '@/stores'
import { reqCreateOrderAPI, reqGenerateOrderAPI } from "@/apis/order";
import { reqUserDeliveryAddrListAPI } from '@/apis/userDeliveryAddr';
import { onShow } from '@dcloudio/uni-app';

// ---------------- 定义全局变量开始 ----------------
// 全局属性
const global:any = inject('global')

// 用户存储
const userStore = useUserStore()

// 购物车存储
const cartStore = useCartStore()

// 订单存储
const orderStore = useOrderStore()

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// ---------------- 定义全局变量结束 ----------------


// 提交数据
const formData = reactive({
	name: '',
    mobile: '',
    date: '',
    note: ''
})

const formRef = ref()

// 验证规则
const rules = {
	name: {
		rules: [{
			required: true,
			errorMessage: '订购人姓名不能为空'
		}]
	}
}


// ------------------ 加载页面开始 ----------------------
// 获取页面参数
const query = defineProps({
    "mode": {
        type: String,
        default: 1
    }
})
const mode:any = ref(1)
onShow(() => {
  mode.value = query.mode
  getUserDeliveryAddr()
})
// ------------------ 加载页面结束 ----------------------



// ------------------ 收货地址功能开始 ------------------
const deliveryAddrList = ref([])
const getUserDeliveryAddr = async () => {
  const result:any = await reqUserDeliveryAddrListAPI({status: 1})
  deliveryAddrList.value = result.data.user_delivery_addrs != null ? result.data.user_delivery_addrs : []
  if (deliveryAddrList.value.length > 0) {
    let deliveryAddr:any = null
    deliveryAddrList.value.forEach((item:any) => {
        if (item.is_default == 1) {
        deliveryAddr = item
        }
    });

    if (!deliveryAddr) {
        deliveryAddr = deliveryAddrList.value[0]
    }


    currentAddrId.value = deliveryAddr.id
    userStore.setDeliveryAddr(deliveryAddr)
  }
}
// ------------------ 收货地址功能结束 ------------------



// ---------------- 选择收货地址功能开始 ----------------
// 定义选择收货地址弹层
const popup:any = ref(null)

// 当前收货地址ID
const currentAddrId = ref(0)

// 处理显示选择收货地址弹层事件
const handleShowChooseDeliveryAddrPopup = () => {
    popup.value.open()
}

// 处理关闭选择收货地址弹层事件
const handleCloseAddressPopup = () => {
    popup.value.close()
}

// 定义处理选择地址事件
const handleChooseDeliveryAddr = (item:any) => {
    currentAddrId.value = item.id
    userStore.setDeliveryAddr(item)
    popup.value.close()
}

// ---------------- 选择收货地址功能结束 ----------------





// ------------------ 创建订单功能开始 ------------------
const handleCreateOrder = async () => {
  if (!userStore.deliveryAddr) {
    uni.showToast({
      icon: 'none',
      title: '请选择收货地址!',
      duration: 1000
    })
    return false
  }
  // 下单参数
  let params:any = {
		platform: 1,
		username: userStore.profile.user.username,
		address_id: userStore.deliveryAddr.id
	}
	
	let result:any = null
	// 直接下单方式
	if (mode.value == 1) {
		const createOrderParams = orderStore.createOrderParams
		// 判断库存
		if (createOrderParams.num > createOrderParams.inventory_num) {
            uni.showToast({
                icon: 'none',
                title: '库存不足',
                duration: 1000
            })
			return false
		}
		
		params.goods_sku_id = createOrderParams.goods_sku_id
		params.num = createOrderParams.num
		result = await reqGenerateOrderAPI(params)
	} else {// 购物车下单方式
		result = await reqCreateOrderAPI(params)
	}
	
	uni.showToast({
		title: '创建订单成功',
		duration: 1000
	})
	
	// 跳转订单支付页面
	uni.navigateTo({
		url: "/pagesOrder/order_detail/index?oid=" + result.data.oid
	})
}
// ------------------ 创建订单功能结束 ------------------



// ------------------ 页面跳转功能开始 ------------------
const goto = (url:any) => {
    popup.value.close()
    uni.navigateTo({url})
}
// ------------------ 页面跳转功能结束 ------------------
</script>

<style lang="scss">
.confirm-order-container {
    background-color: #FAF5F5;
    height: 100%;
    /* 地址区域 */
    .address-wrap {
        background-color: #fff;
        padding: 30rpx 20rpx;
        margin: 20rpx 20rpx 0 20rpx;
        border-radius: 10rpx;
        font-size: 28rpx;
        .address-icon {
            padding-right: 6rpx;
            .iconfont {
                font-size: 50rpx;
                color: #008000;
            }
        }
        .title {
            font-size: 32rpx;
            font-weight: bold;
            padding-bottom: 10rpx;
            border-bottom: 2rpx solid #ccc;
        }

        .content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-top: 20rpx;
            .address-left {
                flex: 1;
                .top {
                    margin-bottom: 10rpx;
                }
                .bottom {
                    .name {
                        margin-right: 10rpx;
                    }
                }
            }
            .address-right {
                width: 50rpx;
                text-align: end;
            }
        }

        .choose {
            text-align: center;
            padding-top: 40rpx;
            .choose-btn {
                padding: 15rpx 80rpx;
                border: 1rpx solid #008000;
                color: #008000;
                border-radius: 10rpx;
            }
        }
    }
    .address-title {
        display: flex;
        align-items: center;
        
        padding: 20rpx;
        border-bottom: 2rpx solid #ccc;
        .title {
            font-size: 34rpx;
            flex: 1;
            text-align: center;
        }
        .close {
            width: 40rpx;
            font-size: 40rpx;
        }
    }

    // 收货地址列表
    .address-list-wrap {
        padding: 20rpx;
        .address-item {
            display: flex;
            justify-content: space-between;

            border: 2rpx solid #ccc;
            border-radius: 10rpx;
            padding: 10rpx;
            margin-bottom: 20rpx;
            .content-left {
                display: flex;
                align-items: center;
                flex: 1;
                .iconfont {
                    font-size: 40rpx;
                    color: #008000;
                    padding-right: 8rpx; 
                }
                .content-box {
                    .top {
                        padding-bottom: 16rpx;
                    }
                    .bottom {
                        .mobile {
                            margin-left: 10rpx;
                        }
                    }
                }
            }
            .content-right {
                width: 80rpx;
            }
        }
        .active {
            border: 2rpx solid #008000;
        }

        // 新增地址按钮
        .add-address {
            text-align: center;
            padding: 20rpx 0 10rpx 0;
            .add-btn {
                padding: 10rpx 60rpx;
                border: 2rpx solid #008000;
                color: #008000;
            }
        }
    }

    .order-wrap {
        background-color: #fff;
        padding: 30rpx 20rpx;
        margin: 20rpx;
        border-radius: 10rpx;
        .uni-easyinput__content {
            border-bottom: 2rpx solid #ccc;
        }
    }

    .goods-wrap {
        background-color: #fff;
        padding: 30rpx 20rpx;
        margin: 20rpx;
        border-radius: 10rpx;
        .goods-item {
            display: flex;

            &:first-child {
                padding-top: 0;
            }
            &:last-child {
                border-bottom: none;
                padding-bottom: 0;
            }
            padding: 14rpx 0;
            border-bottom: 2rpx dashed #ccc;
            .cover-box {
                width: 100rpx;
                height: 100rpx;
                .cover {
                    width: 100%;
                    height: 100%;
                }
            }
            .goods-box {
                flex: 1;
                padding-left: 10rpx;
                .top {
                    font-size: 28rpx;
                }
                .sku-txt {
                    font-size: 22rpx;
                    background-color: #F7F7F8;
                    padding: 4rpx;
                }
                .bottom {
                    display: flex;
                    justify-content: space-between;
                    margin-top: 10rpx;
                    .price-box {
                        color: #CD0011;
                    }
                }
            }
        }
    }

    .footer-wrap {
        height: 90rpx;
        padding: 0 20rpx;

        position: fixed;
        left: 0;
        right: 0;
        bottom: calc(var(--window-bottom));
        background-color: #fff;
        border-top: 1rpx solid #ccc;

        display: flex;
        justify-content: space-between;
        align-items: center;
        box-sizing: content-box;
        .left {
            color: #CD0011;
            .price {
                font-size: 36rpx;
            }
        }
        .right {
            .btn {
                width: 160rpx;
                height: 60rpx;
                line-height: 60rpx;
                background-color: #CD0011;
                color: #fff;
                font-size: 24rpx;
                border-radius: 30rpx;
            }
        }
    }
}
</style>